<template>
  <view class="myTodoList">
    <view class="top">
      <img style="width: 80%; margin: 0 auto"
        src="https://nfzjszlb.jst.zj.gov.cn/serverfile/zheliban/icon/YPC/12.png" />
      <p>
        <span style="
            width: 31%;
            display: inline-block;
            text-align: left;
            padding-left: 0%;
          ">鉴定申请</span>
        <span style="width: 31%; display: inline-block; text-align: center">合同签订</span>
        <span style="
            width: 31%;
            display: inline-block;
            text-align: center;
            padding-left: 12%;
          ">房屋整治</span>
      </p>
    </view>
    <view class="backgrounds"> </view>
    <view class="tabs" v-show="isShow">
      <van-tabs ref="tabs" v-model="active" @click="handleclickto" color="dodgerblue" line-width="80px"
        background="#eee" title-active-color="dodgerblue">
        <van-tab title="线上签合同">
          <!-- <view class="" v-for="(item,index) in QY" :key="index">
						<u-cell size="large" :title="item.lable" :value="ListData[item.key]"></u-cell>
					</view> -->
          <u--form labelPosition="left" :model="ListData[0]" ref="form1" v-for="(item, index) in QY" :key="index"
            labelWidth="200">
            <u-form-item :label="item.lable" :required="item.isrequired" :prop="item.key" borderBottom ref="item1">
              <u--input v-model="ListData[0][item.key]" :placeholder="'请输入' + item.lable" border="none"></u--input>
            </u-form-item>
          </u--form>
        </van-tab>
        <van-tab title="纸质合同上传">
          <view style="padding: 0.4rem">
            <u-cell-group>
              <u-cell size="large" title="合同文件" :value="FILENAME" label="支持pdf\word等文件格式上传"></u-cell>
              <u-upload accept="file" @afterRead="afterRead" @delete="deletePic" :previewImage="false"
                :fileList="fileList6" name="6" multiple :maxCount="1" width="100">
                <view style="position: absolute; right: 0; top: 1.7rem">
                  <u-button size="small" type="primary" :plain="true" text="上传"></u-button>
                </view>
              </u-upload>
            </u-cell-group>
            <u-cell-group>
              <u-cell size="large" title="合同照片" value="" label="如果上传了合同文件不必再拍照上传"></u-cell>
              <view style="padding: 0.6rem">
                <u-upload @afterRead="afterRead1" accept="image" @delete="deletePic1" :fileList="fileList1"
                  :previewFullImage="true" :previewImage="true" name="1" multiple :maxCount="10" width="320rpx"
                  height="200rpx"></u-upload>
              </view>
            </u-cell-group>
          </view>
          <view class="footer">
            <u-button @click="handleSend" type="primary" style="width: 90%" :plain="true" text="提交"></u-button>
          </view>
        </van-tab>
      </van-tabs>
    </view>
    <view class="buttons" v-if="isShow2">
      <u-button @click="handlebutton('0')" type="primary" style="width: 16%" :plain="true" text="保存"></u-button>
      <u-button @click="handlebutton('1')" type="primary" style="width: 16%" :plain="true" text="预览"></u-button>
      <u-button @click="handlebutton('2')" type="primary" style="width: 16%" :plain="true" text="签字"></u-button>
      <u-button @click="handlebutton('3')" type="primary" style="width: 16%" :plain="true" text="提交"></u-button>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import {
  getDatalistForTree,
  ECAOpenDataView,
  ECAinsertDataView,
  ECAFileServerUpload,
  ECAPrepareGetFilesInfo,
  ECAPrepareLoadWorkflowScript,
  ECAPLoadSendFormData,
  ECAPlatSendTask,
  ECAExecProcedure,
  HXSignForPlatForm
} from "@/common/utils/api.js";
import qs from "qs";
export default {
  data() {
    return {
      active: ["1"],
      isShow: false,
      isShow2: true,
      FILENAME: "",
      fileList6: [],
      fileList1: [],
      row: [],
      ListData: [{
        i_pkid: "",
        i_jfmc: "",
        i_rhzfyf: "",
        i_jftxdz: "",
        i_wtfybjdfwgx: "",
        i_yfmc: "",
        i_yflxfs: "",
        i_yftxdz: "",
        i_bjdfwgk: "",
        i_sfydsrczjf: "",
        i_sfsjzc: "",
        i_qtsmqk: "",
        i_zj: "",
        i_jflxfs: "",
        i_yfkhyhmc: "",
        i_yhzh: ""
      }],
      QY: [
        {
          lable: "甲方",
          name: "浙江政欣工程设计有限公司",
          key: "i_jfmc",
          isrequired: true,
        },
        {
          lable: "联系方式",
          name: "010-665456276",
          key: "i_jflxfs",
          isrequired: true,
        },
        {
          lable: "通讯地址",
          name: "浙江省杭州市临安区玲珑街道陈村村",
          key: "i_jftxdz",
          isrequired: true,
        },

        {
          lable: "委托方与被鉴定房屋关系",
          name: "自有",
          key: "i_wtfybjdfwgx",
          isrequired: true,
        },
        {
          lable: "乙方",
          name: "蒋海燕",
          key: "i_yfmc",
          isrequired: true,
        },
        {
          lable: "联系方式",
          name: "16635049159",
          key: "i_yflxfs",
          isrequired: true,
        },
        {
          lable: "通讯地址",
          name: "浙江省杭州市临安区玲珑街道陈村村",
          key: "i_yftxdz",
          isrequired: true,
        },
        {
          lable: "被鉴定房屋概况",
          name: "良好",
          key: "i_bjdfwgk",
          isrequired: true,
        },
        {
          lable: "是否与第三人存在纠纷",
          name: "否",
          key: "i_sfydsrczjf",
          isrequired: true,
        },
        {
          lable: "是否涉及仲裁或司法诉讼",
          name: "否",
          key: "i_sfsjzc",
          isrequired: true,
        },
        {
          lable: "其他需要说明的情况",
          name: "无",
          key: "i_qtsmqk",
          isrequired: true,
        },
        {
          lable: "总价",
          name: "1000万",
          key: "i_zj",
          isrequired: true,
        },
        {
          lable: "如何支付乙方",
          name: "银行转账",
          key: "i_rhzfyf",
          isrequired: true,
        },
        {
          lable: "乙方开户银行名称",
          name: "*******支行",
          key: "i_yfkhyhmc",
          isrequired: true,
        },
        {
          lable: "银行账号",
          name: "33*******************239",
          key: "i_yhzh",
          isrequired: true,
        },
      ],
    };
  },
  watch: {
    isShow(val) {
      this.$nextTick(() => {
        this.$refs.tabs.resize();
      });
    },
  },
  onShow() {

  },
  methods: {
    handleclickto(e) {
      if (e.detail.index == 0) {
        this.isShow2 = true;
      } else {
        this.isShow2 = false;
      }
    },
    async handlebutton(data) {
      if (data == "0") {
        this.ECAExecProcedure()
      } else if (data == "1") {
        uni.navigateTo({
          url: "/pages/pdfView/pdfView?src=" + (this.row.ROW_GUID),
        });
      } else if (data == "2") {
        // this.showToast1();
        let url = `https://nfzjszlb.jst.zj.gov.cn/eca/fwjd/PrintServer/api/PreviewWordRpt?groupGuid=%7BFA599DFB-ED68-4AC4-861E-46BD947B79CE%7D&toRowGuid=${this.row.ROW_GUID}&token=`+uni.getStorageSync('token')
        //在线签字todo
        let params2 = {
          callbackUrl: 'https://nfzjszlb.jst.zj.gov.cn/tyzcpt/', //可以写死
          callbackParam: "fileGuid=bed4afda-d7c8-45a2-ac58-068ee5e3f832", //可以写死
          fileUrl: url,
          isPerson: "1", //可以写死
          pdfFileFlag: this.row.ROW_GUID,
          personDTO: {
            handSignWay: "0",
            isFreeSign: "0",
            username: this.row.SQR,
            mobile: this.row.PHONE,
            idnum: this.row.SFZH,
            idType: "1",
            signPositionDTO: {
              keyword: "承包人(签字或者盖章)",
              llx: "110",
              lly: "0",
            },
          },
        };
        const res1 = await HXSignForPlatForm(params2);
      } else if (data == "3") {
        this.handleSend()
      }
    },
    //签合同
    async handleSend() {
      let time = Date.now();
      const res = ECAPrepareGetFilesInfo(this.row.ROW_GUID, time);
      const res1 = ECAPrepareLoadWorkflowScript(this.row.TASK_ID, time, "");
      const res2 = await ECAPLoadSendFormData(this.row.TASK_ID, time);
      let data3 = {
        procName: "get_user_by_taskId",
        dtParams: JSON.stringify([{
          "i_taskId": this.row.TASK_ID,
          "i_type": 0
        }]),
      }
      const user = await ECAExecProcedure(data3)
      let data2 = {
        taskId: this.row.TASK_ID,
        direction: 0,
        wfBoxGuid: "82c1d3c7-f56a-4414-8382-f06e13a9772e",
        actionText: "",
        taskName: "",
        wfGuid: "{48A968B4-A044-4115-A9DB-099029B2E011}",
        sendNodes: JSON.stringify([
          {
            TNID: 2,
            PTNID: 1,
            TEXT: user.Data[0]._USERNAME,
            WFNODEGUID: "{91A7427E-13ED-489F-AF84-5B0C9250855C}",
            WFNODETYPE: 2,
            WFNODENAME: "个人签合同",
            ISUSER: 1,
            USERID: user.Data[0]._USERID,
            USERNAME: user.Data[0]._USERNAME,
            SINGLEASSIGN: true,
            PREJUNCNODEGUID: "",
            SORTNUM: 0,
            selected: true,
          },
        ]),
        time,
      };
      //拿到takid
      const res5 = await ECAPlatSendTask(data2);
      if (res5.Success) {
        this.showToast2();
        // setTimeout(() => {
        //   this.$nextTick(() => {
        //     uni.navigateTo({
        //       url: "/",
        //       animationType: "fade-in",
        //     });
        //   });
        // }, 1000);
      }
    },
    showToast(params) {
      this.$refs.uToast.show({
        message: "保存成功",
        type: "success",
      });
    },
    showToast2(params) {
      this.$refs.uToast.show({
        message: "发送成功",
        type: "success",
      });
    },
    showToast4(params) {
      this.$refs.uToast.show({
        message: "上传成功",
        type: "success",
      });
    },
    showToast1(params) {
      this.$refs.uToast.show({
        message: "功能暂未开放",
        type: "error",
      });
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    showToast8(params) {
      this.$refs.uToast.show({
        message: "不支持此类型文件上传",
        type: "error",
      });
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      console.log(this.FILENAME)
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map(async (item) => {
        if (item.name.indexOf('pdf') != -1 || item.name.indexOf('doc') != -1) {
          this.FILENAME = event.file[0].name
          this[`fileList${event.name}`].push({
            ...item,
            status: "uploading",
            message: "上传中",
          });
          for (let i = 0; i < lists.length; i++) {
            const result = await this.uploadFilePromise(lists[i].url);
            console.log(result);
            let item = this[`fileList${event.name}`][fileListLen];
            this[`fileList${event.name}`].splice(
              fileListLen,
              1,
              Object.assign(item, {
                status: "success",
                message: "",
                url: result,
              })
            );
            fileListLen++;
          }
        } else {
          this.showToast8()
          return
        }
      });
    },
    async uploadFilePromise(file) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url:
            "https://nfzjszlb.jst.zj.gov.cn/eca/fwjd/FileServer/api/Upload?token=" +
            uni.getStorageSync("token"), // 仅为示例，非真实的接口地址
          filePath: file,
          name: "file",
          formData: {
            toRowGuid: this.row.ROW_GUID,
            groupGuid: "8ae061e7-ad06-48ec-bae4-5ba0732a4d77",
            token: uni.getStorageSync("token"),
          },
          success: (res) => {
            setTimeout(() => {
              this.showToast4();
              resolve(res);
            }, 1000);
            //上传成功后调用存储过程
            this.ECAExecProcedure1();
          },
        });
      });
    },
    async afterRead1(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map(async (item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise1(lists[i].url);
        console.log(result);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    async uploadFilePromise1(file) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url:
            "https://nfzjszlb.jst.zj.gov.cn/eca/fwjd/FileServer/api/Upload?token=" +
            uni.getStorageSync("token"), // 仅为示例，非真实的接口地址
          filePath: file,
          name: "file",
          formData: {
            toRowGuid: this.row.ROW_GUID,
            groupGuid: "8ae061e7-ad06-48ec-bae4-5ba0732a4d77",
            token: uni.getStorageSync("token"),
          },
          success: (res) => {
            setTimeout(() => {
              this.showToast4();
              resolve(res);
            }, 1000);
            //上传成功后调用存储过程
            this.ECAExecProcedure1();
          },
        });
      });
    },
    async ECAExecProcedure1() {
      let time = Date.now();
      let data = {
        procName: "up_ht_by_pkid",
        dtParams: JSON.stringify([{ "i_type": 0, "i_ht_type": 5, "i_pkid": this.row.PKID }]),
        time: time,
        viewParameter: {},
      };
      const res = await ECAExecProcedure(data)
    },
    async ECAExecProcedure() {
      this.ListData[0].i_pkid = this.row.PKID
      let time = Date.now();
      let data = {
        procName: "out_update_zxwtsqb_by_pkid",
        dtParams: JSON.stringify(this.ListData),
        time: time,
        viewParameter: {},
      };
      const res = await ECAExecProcedure(data)
      this.showToast()
    },
    //回显
    async getListData() {
      let ListData = [{
        i_pkid: null,
        i_jfmc: null,
        i_rhzfyf: null,
        i_jftxdz: null,
        i_wtfybjdfwgx: null,
        i_yfmc: null,
        i_yflxfs: null,
        i_yftxdz: null,
        i_bjdfwgk: null,
        i_sfydsrczjf: null,
        i_sfsjzc: null,
        i_qtsmqk: null,
        i_zj: null,
        i_jflxfs: null,
        i_yfkhyhmc: null,
        i_yhzh: null
      }]
      ListData[0].i_pkid = this.row.PKID
      let time = Date.now();
      let data = {
        procName: "out_update_zxwtsqb_by_pkid",
        dtParams: JSON.stringify(ListData),
        time: time,
        viewParameter: {}
      }
      const res = await ECAExecProcedure(data)
      if (res.OutParams) {
        // this.ListData = res.Data
        this.ListData = []
        let newArr = this.lowerJSONKey(...res.Data)
        this.$set(this.ListData, 0, newArr);
        this.$forceUpdate()
      }
      console.log(this.ListData)
    },
    lowerJSONKey(jsonObj) {
      for (var key in jsonObj) {
        jsonObj[key.toLowerCase()] = jsonObj[key];
        delete (jsonObj[key]);
      }
      return jsonObj;
    }
  },
  onLoad(data) {
    this.row = JSON.parse(data.data);
    this.getListData()
    console.log(this.row);
    this.isShow = false;
    this.$nextTick(() => {
      this.isShow = true;
    });
    if (ZWJSBridge) {
      ZWJSBridge.setTitle({
        title: "签订合同",
      })
        .then((res) => { })
        .catch((err) => { });
    }
  },
};
</script>

<style lang="scss">
.myTodoList {
  height: 100vh;

  .backgrounds {
    height: 1rem;
    background: #eee;
  }

  .top {
    height: 30px;
    background: #ffffff;
    margin-bottom: 20px;
    padding-top: 25px;
    text-align: center;

    .origin {
      width: 22px;
      height: 22px;
      background: #007aff;
      border-radius: 50%;
      display: inline-block;
    }

    .line {
      width: 20vw;
      /*height: 1px;*/
      border: 1px dashed #007aff;
      display: inline-block;
    }
  }

  .tabs {
    height: 83vh;
    overflow: auto;
    padding: 0 40rpx;
  }

  .buttons {
    padding-top: 0.4rem;
    display: flex;
    justify-content: center;
  }

  ::v-deep .uni-input-input {
    text-align: right;
  }
}
</style>
